local addon, ns = ...
local C = ns.shared.color
local L = ns.L
local func = ns.shared

local tooltip = nil
local guildUpdateFreq = 300
local ttColumns = 5

local guild_events = {
	"PLAYER_LOGIN",
	"GUILD_ROSTER_UPDATE",
	"PLAYER_ENTERING_WORLD",
	"GUILD_XP_UPDATE",
	"CHAT_MSG_SYSTEM"

}

-- function to refresh the guild roster cache
local function guildOnUpdate()
	if IsInGuild() then 
		GuildRoster()
		QueryGuildXP()
	end
end

local guild_onevent = function (self, event, msg)
	local dataobj = self.obj or LibStub:GetLibrary("LibDataBroker-1.1"):GetDataObjectByName(L["Guild"])
	if not IsInGuild() then
		dataobj.text = L["No Guild"]
		return
	end

	if CanViewOfficerNote() then ttColumns = 6 end

	if event == "PLAYER_LOGIN" or event == "PLAYER_ENTERING_WORLD" then
		guildOnUpdate()
	end

	if event == "CHAT_MSG_SYSTEM" then
		if string.find(msg, L["has come online"]) or string.find(msg, L["has gone offline"]) then
			local totalGuildMembers, membersOnline = GetNumGuildMembers()
			dataobj.text = membersOnline .. "/" .. totalGuildMembers
		end
	end

	if event == "GUILD_ROSTER_UPDATE" or event == "GUILD_XP_UPDATE" then
		local totalGuildMembers, membersOnline = GetNumGuildMembers()
		dataobj.text = membersOnline .. "/" .. totalGuildMembers
	end
end


-- Function to draw the guild tooltip
local function drawGuildTip()
	if Broker_EverythingDB[L["Guild"]].showXP == nil then Broker_EverythingDB[L["Guild"]].showXP = true end

	if not IsInGuild() then
		tooltip:AddHeader(L["Guild"])
		tooltip:AddLine(L["No Guild"])
		return
	end
-- XP & Reputation

	local currentXP, nextLevelXP, dailyXP, maxDailyXP, unitWeeklyXP, unitTotalXP = UnitGetGuildXP("player");

--	print("Current Guild XP: " .. tostring(currentXP) .. ", total: " .. tostring(nextLevelXP + currentXP) .. ", daily: " .. tostring(dailyXP) .. ", daily max: " .. tostring(maxDailyXP));
--	print("Player weekly contribution: " .. tostring(unitWeeklyXP) .. ", total contribution: " .. tostring(unitTotalXP));

	local name, description, standingID, barMin, barMax, barValue = GetGuildFactionInfo()
	local factionStandingtext = GetText("FACTION_STANDING_LABEL"..standingID)

	local guildName = GetGuildInfo("player")
	local guildLevel = GetGuildLevel()
	local gMOTD = GetGuildRosterMOTD()

	if gMOTD:len() > 100 then
		gMOTD = func.splitText(gMOTD, ".")
	end

	local line, column = tooltip:AddHeader()
	tooltip:SetCell(line, 1, C.dkyellow(string.format("%s: [%s]", L["Guild"], guildName)), nil, nil, ttColumns)

	line, column = tooltip:AddLine()
	tooltip:SetCell(line, 1, string.format("%s %s: %d", L["Guild"], L["Level"], guildLevel), nil, nil, ttColumns)

	line, column = tooltip:AddLine()
	tooltip:SetCell(line, 1, C.ltyellow(L["Message of the Day"]), nil, nil, ttColumns)
	
	line, column = tooltip:AddLine()
	tooltip:SetCell(line, 1, C.ltyellow(gMOTD), nil, nil, ttColumns)	
	
	line, column = tooltip:AddLine(" ")


	if Broker_EverythingDB[L["Guild"]].showXP == true then 	
		line, column = tooltip:AddLine()
		tooltip:SetCell(line, 1, string.format("%s:", C.ltblue(L["XP"])))
		tooltip:SetCell(line, 2, string.format("%s/%s", currentXP, currentXP + nextLevelXP),nil, nil, 2)
		
	--[[	if dailyXP == maxDailyXP then
			--line, column = tooltip:AddLine()
			tooltip:SetCell(line, 4, C.red(L["No more guild XP can be earned today."]), nil, nil, ttColumns-3) -- No more guild XP can be earned today.
		else
			--line, column = tooltip:AddLine()
			tooltip:SetCell(line, 4, string.format("%s: %s.",  L["XP can be earned today"], maxDailyXP - dailyXP), nil, nil, ttColumns - 3)
		end		
	]]
		line, column = tooltip:AddLine()
		tooltip:SetCell(line, 1, string.format("%s:", C.ltblue(L["Rep"])))
		tooltip:SetCell(line, 2, string.format("%s: (%d/%d)", factionStandingtext, barValue, barMax), nil, nil, ttColumns - 1)
		tooltip:AddLine(" ")
		
	
		tooltip:AddLine(" ")
		
	end
		line, column = tooltip:AddLine()
	if ttColumns == 6 then
		--tooltip:AddLine(C.ltyellow(L["Level"]), C.ltyellow(L["Online"]), C.ltyellow(L["Zone"]), C.ltyellow(L["Notes"]), C.ltyellow(L["Officer's Notes"]), C.ltyellow(L["Rank"]))
		tooltip:SetCell(line, 1, C.ltyellow(L["Level"]), nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
		tooltip:SetCell(line, 2, C.ltyellow(L["Online"]), nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
		tooltip:SetCell(line, 3, C.ltyellow(L["Zone"]), nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
		tooltip:SetCell(line, 4, C.ltyellow(L["Notes"]), nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
		tooltip:SetCell(line, 5, C.ltyellow(L["Officer's Notes"]), nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
		tooltip:SetCell(line, 6, C.ltyellow(L["Rank"]), nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
	else
		--tooltip:AddLine(C.ltyellow(L["Level"]), C.ltyellow(L["Online"]), C.ltyellow(L["Zone"]), C.ltyellow(L["Notes"]), C.ltyellow(L["Rank"]))
		tooltip:SetCell(line, 1, C.ltyellow(L["Level"]), nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
		tooltip:SetCell(line, 2, C.ltyellow(L["Online"]), nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
		tooltip:SetCell(line, 3, C.ltyellow(L["Zone"]), nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
		tooltip:SetCell(line, 4, C.ltyellow(L["Notes"]), nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
		tooltip:SetCell(line, 5, C.ltyellow(L["Rank"]), nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
	end

	tooltip:AddSeparator()
	local y = GetNumGuildMembers(true)	
	for i = 1, y do
		local n, r, ri, l, c, z, no, ono, o, s, ec = GetGuildRosterInfo(i)
		
		if o then
			if s == 0 then
				s = ""
			elseif s== 1 then
				s = "[AFK]"
			elseif s == 2 then
				s = "[DND]"
			end
			local name = string.format("%s %s", s or "", n)

			line, column = tooltip:AddLine()
			if ttColumns == 6 then
				--line, column = tooltip:AddLine(l, C.className(name, ec), z or "",  no or "", ono or "" ,C.grey(r))
				tooltip:SetCell(line, 1, l, nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
				tooltip:SetCell(line, 2, C.className(name, ec), nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
				tooltip:SetCell(line, 3,  z or "", nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
				tooltip:SetCell(line, 4, no or "", nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
				tooltip:SetCell(line, 5, ono or "" , nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
				tooltip:SetCell(line, 6, C.grey(r), nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
			else 
				--line, column = tooltip:AddLine(l, C.className(name, ec), z or "",  no or "", C.grey(r))
				tooltip:SetCell(line, 1, l, nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
				tooltip:SetCell(line, 2, C.className(name, ec), nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
				tooltip:SetCell(line, 3,  z or "", nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
				tooltip:SetCell(line, 4, no or "", nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
				tooltip:SetCell(line, 5, C.grey(r) , nil, nil, 1, LibQTip.LabelProvidor, 0, 10)
			end
			tooltip:SetLineScript(line, "OnMouseUp", function(self) if IsAltKeyDown() then InviteUnit(n) else SetItemRef("player:"..name, "|Hplayer:"..name.."|h["..name.."|h", "LeftButton") end end, n)			
			tooltip:SetLineScript(line, "OnEnter", function(self) tooltip:SetLineColor(line, 1,192/255, 90/255, 0.3) end )
			tooltip:SetLineScript(line, "OnLeave", function(self) tooltip:SetLineColor(line, 0,0,0,0) end)
		end
	end
	tooltip:AddLine(" ")

	line, column = tooltip:AddLine()
	tooltip:SetCell(line, 1, C.dkgreen(L["Hint: Left-click icon to open the guild roster."]), nil, nil, 5)
	
	line, column = tooltip:AddLine()
	tooltip:SetCell(line, 1, C.dkgreen(L["Click guild member to whisper."]), nil, nil, 5)
	
	line, column = tooltip:AddLine()
	tooltip:SetCell(line, 1, C.dkgreen(L["Alt + Click guild member to invite."]), nil, nil, 5)

	line, column = tooltip:AddLine()
	tooltip:SetCell(line, 1, C.dkgreen(L["Right-click to hide/show the guild xp details."]), nil, nil, 5)
	
	line, column = nil, nil
	

end

 -- function to set onenter and onleave functions.
local guild_init = function(obj)
	if not obj then return end

	obj = obj.obj or LibStub:GetLibrary("LibDataBroker-1.1"):GetDataObjectByName(L["Guild"])
	
	obj.OnLeave = function()
		if tooltip then
			if MouseIsOver(tooltip) then
					tooltip:SetScript('OnLeave', func.hideTooltip)
			else
					func.hideTooltip(tooltip)
			end
		end
  	end

	obj.OnEnter = function(self)
		tooltip = LibQTip:Acquire("GuildTT", ttColumns, "LEFT", "LEFT", "CENTER", "LEFT", "LEFT", "LEFT") 
		tooltip:Clear()
		drawGuildTip()
		func.createTooltip(self,tooltip)
	end
end


local guild_onclick = function(self, btn)
	if btn == "RightButton" then 
		if Broker_EverythingDB[L["Guild"]].showXP == true then 
			Broker_EverythingDB[L["Guild"]].showXP = false
		else
			Broker_EverythingDB[L["Guild"]].showXP = true
		end

		if tooltip ~= nil then
			func.hideTooltip(tooltip)
			tooltip = LibQTip:Acquire("GuildTT", ttColumns, "LEFT", "LEFT", "CENTER", "LEFT", "LEFT", "LEFT") 
			tooltip:Clear()
			drawGuildTip()
			func.createTooltip(self,tooltip)

	--		tooltip:Clear()
	--		drawGuildTip()
		end 
	elseif GUILockDown == nil then 
		ToggleGuildFrame()
	elseif GUILockDown == 1 then 
		return 
	end
end


Broker_Everything:Register(L["Guild"],
	GetItemIcon(5976),
	guild_init,
	guild_onevent,
	guild_events,
	guild_onclick,
	0,
	guildOnUpdate,
	guildUpdateFreq)

